package com.self.member.config;

import com.alibaba.fastjson.JSONObject;
import com.self.common.exception.BusinessException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @version v1.0
 * @ClassName: IdAutoConfiguration
 * @Description:
 * @Author: Mac
 * @Date: 2022/6/18 9:25
 */
@Configuration
@EnableConfigurationProperties(IdProperties.class)
public class IdAutoConfiguration {

    private static IdProperties idProperties;

    private static RestTemplate restTemplate;

    public IdAutoConfiguration(IdProperties idProperties,RestTemplate restTemplate) {
        IdAutoConfiguration.idProperties = idProperties;
        IdAutoConfiguration.restTemplate = restTemplate;
    }

    public static boolean check(String realName ,String cardNum){
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
        params.add("idcard", cardNum);
        params.add("name", realName);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.set("Authorization", "APPCODE " + idProperties.getAppCode());
        HttpEntity httpEntity = new HttpEntity(params,httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(idProperties.getUrl(), HttpMethod.POST, httpEntity, String.class);
        if (HttpStatus.OK == exchange.getStatusCode()){
            String body = exchange.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            String code = jsonObject.getString("code");
            if ("0".equals(code)){
                JSONObject  result = jsonObject.getJSONObject("result");
                if (result != null && "1".equals(result.getString("res"))){
                    return true;
                }
                throw new BusinessException(result == null?"认证失败，请重新认证":result.getString("description"));
            }else {
                throw new BusinessException(jsonObject.getString("message"));
            }
        }else{
            throw new BusinessException("认证请求网络异常");
        }
    }
}
